/* eslint-disable array-callback-return */
import React from 'react';
import { DeleteOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Input, Upload, Select, Button, Divider, message } from 'antd';
import HOCSelect from '@/components/AntDesign/Select';
import { requestHeadersMd5 } from '@/utils/utils';

const FormItem = Form.Item;
const { Option } = Select;
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      listIndex: 0,
      invoiceList: [],
      isRequiredForm: [true],
      uploadUrl: '/csApi/fileServer/uploadFile',
      downloadUrl: '/csApi/fileServer/downloadFile',
      invoiceAffixList: {},
    };
  }

  componentDidMount = () => {
    this.add();
  };

  // 新增数据
  add = () => {
    const { invoiceList, listIndex, isRequiredForm } = this.state;
    const newData = invoiceList.map(item => ({ ...item }));
    newData.push({
      id: `list_${listIndex}`,
      isRequired: true,
      vatCoprName: '增值税单位名称',
      invTypeName: '发票类型',
      taxerIdNo: '纳税人识别号',
      bankOfDepoName: '开户行',
      bankAcco: '银行账号',
      invPhone: '开票电话',
      invAddr: '开票地址',
      remark: '备注',
    });
    this.state.listIndex += 1;
    const cRequiredForm = isRequiredForm;
    cRequiredForm.push(true);
    this.setState({ invoiceList: newData, isRequiredForm: cRequiredForm });
  };

  // 删除数据
  delList = id => {
    const { invoiceList } = this.state;
    const newData = invoiceList.filter(item => item.id !== id);
    this.setState({ invoiceList: newData });
  };

  // 选择发票类型
  selectTaxerType = (value, id) => {
    const { invoiceList } = this.state;
    const newData = invoiceList;
    newData.map(item => {
      const temp = item;
      if (item.id === id && value.key === '1') {
        temp.isRequired = true;
      } else if (item.id === id && value.key !== '1') {
        temp.isRequired = false;
      }
    });
    this.setState({ invoiceList: newData });
  };

  // 文件上传
  changeUpload = (info, listContFile, listId) => {
    const { file, fileList } = info;
    const { downloadUrl } = this.state;
    const { getAffixList } = this.props;
    const newData = [];
    const newSumFileList = listContFile;
    if (file.status === 'done' && file.response.success) {
      const fileId = file.response.data.split('|')[0];
      const fileName = file.response.data.split('|')[1];
      fileList.map(files => {
        const temp = files;
        temp.url = `${downloadUrl}?fileId=${fileId}&fileName=${fileName}`;
        temp.linkProps = { download: `${fileName}` };
      });
      newData.push({
        uid: file.uid,
        custAffixId: fileId,
        affixName: fileName,
      });
      newSumFileList[listId] = newSumFileList[listId]
        ? newSumFileList[listId].concat(newData)
        : newData;
      this.setState({ invoiceAffixList: newSumFileList });
      getAffixList(newSumFileList);
      message.success('文件上传成功！');
    }

    if (file.status === 'error') {
      message.error('上传失败！');
    }
  };

  // 移除文件
  removeFile = (file, listContFile, listId) => {
    const { getAffixList } = this.props;
    const newSumFileList = listContFile;
    newSumFileList[listId] = newSumFileList[listId].filter(item => item.uid !== file.uid);
    this.setState({ invoiceAffixList: newSumFileList });
    getAffixList(newSumFileList);
  };

  render() {
    const {
      form: { getFieldDecorator },
      invTypeList,
    } = this.props;
    const { uploadUrl, invoiceList, invoiceAffixList } = this.state;
    const xl = { span: 8 };
    const lg = { span: 8 };
    const md = { span: 8 };
    const sm = 24;
    const colProps = { xl, lg, md, sm };
    // 下拉选项
    // 发票类型
    const taxerTypeOL = invTypeList.map(options => (
      <Option key={options.itemCode}>{options.itemName}</Option>
    ));
    return (
      <Form layout="vertical">
        {invoiceList.map((invoiceData, index) => (
          <div key={invoiceData.id}>
            {index ? <Divider /> : ''}
            <Row gutter={64}>
              <Col {...colProps}>
                <FormItem label={invoiceData.vatCoprName}>
                  {getFieldDecorator(`vatCoprName_${invoiceData.id}`, {
                    rules: [{ required: true, message: '输入的内容必须在1-100个字' }],
                  })(<Input placeholder="请输入" maxLength={100} />)}
                </FormItem>
              </Col>
              <Col {...colProps}>
                <FormItem label={invoiceData.invTypeName}>
                  {getFieldDecorator(`invType_${invoiceData.id}`, {
                    rules: [{ required: true, message: '请选择' }],
                  })(
                    <HOCSelect
                      placeholder="请选择"
                      labelInValue
                      showSearch
                      optionFilterProp="children"
                      onChange={value => this.selectTaxerType(value, invoiceData.id)}
                    >
                      {taxerTypeOL}
                    </HOCSelect>
                  )}
                </FormItem>
              </Col>
              <Col {...colProps}>
                <FormItem label={invoiceData.taxerIdNo}>
                  {getFieldDecorator(`taxerIdNo_${invoiceData.id}`, {
                    rules: [
                      {
                        required: true,
                        message: '最大长度不超过18位的数字或字母',
                        pattern: /^[a-zA-Z0-9]{1,18}$/,
                      },
                    ],
                  })(<Input placeholder="请输入" maxLength={19} />)}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={64}>
              <Col {...colProps}>
                <FormItem label={invoiceData.bankOfDepoName}>
                  {getFieldDecorator(`bankOfDepoName_${invoiceData.id}`, {
                    rules: [
                      { required: invoiceData.isRequired, message: '请输入的内容必须在1-100个字' },
                    ],
                  })(<Input placeholder="请输入" maxLength={100} />)}
                </FormItem>
              </Col>
              <Col {...colProps}>
                <FormItem label={invoiceData.bankAcco}>
                  {getFieldDecorator(`bankAcco_${invoiceData.id}`, {
                    rules: [
                      {
                        required: invoiceData.isRequired,
                        message: '最大长度不超过25位数字',
                        pattern: /^\d{1,25}$/,
                      },
                    ],
                  })(<Input placeholder="请输入" maxLength={25} />)}
                </FormItem>
              </Col>
              <Col {...colProps}>
                <FormItem label={invoiceData.invPhone}>
                  {getFieldDecorator(`invPhone_${invoiceData.id}`, {
                    rules: [
                      {
                        required: invoiceData.isRequired,
                        message: '固话或手机',
                        pattern: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,12}$/,
                      },
                    ],
                  })(<Input placeholder="请输入" maxLength={12} />)}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={64}>
              <Col {...colProps}>
                <FormItem label={invoiceData.invAddr}>
                  {getFieldDecorator(`invAddr_${invoiceData.id}`, {
                    rules: [
                      { required: invoiceData.isRequired, message: '请输入的内容必须在1-100个字' },
                    ],
                  })(<Input placeholder="请输入" maxLength={100} />)}
                </FormItem>
              </Col>
              <Col {...colProps}>
                <FormItem label={invoiceData.remark}>
                  {getFieldDecorator(`remark_${invoiceData.id}`, {
                    rules: [{ required: false, message: '请输入的内容必须在1-200个字' }],
                  })(<Input placeholder="请输入" maxLength={200} />)}
                </FormItem>
              </Col>
              <Col {...colProps} style={{ textAlign: 'center' }}>
                {index > 0 && (
                  <Row>
                    <Col {...colProps} />
                    <Col {...colProps} />
                    <Col {...colProps} style={{ textAlign: 'center' }}>
                      <DeleteOutlined
                        className="dynamic-delete-button"
                        style={{ fontSize: '20px', lineHeight: '85px' }}
                        onClick={() => this.delList(invoiceData.id)} 
                      />
                    </Col>
                  </Row>
                )}
              </Col>
            </Row>
            <Row gutter={64}>
              <Col {...colProps}>
                <Form.Item label="附件">
                  {getFieldDecorator(`invoiceLicense_${invoiceData.id}`, {
                    rules: [{ required: false, message: '请输入' }],
                  })(
                    <Upload
                      action={uploadUrl}
                      headers={requestHeadersMd5()}
                      onChange={info => this.changeUpload(info, invoiceAffixList, invoiceData.id)}
                      onRemove={file => this.removeFile(file, invoiceAffixList, invoiceData.id)}
                    >
                      <Button>
                        <UploadOutlined /> 上传附件
                      </Button>
                    </Upload>
                  )}
                </Form.Item>
              </Col>
            </Row>
          </div>
        ))}
        <Button
          style={{ width: '100%', marginBottom: 8 }}
          type="dashed"
          icon={<PlusOutlined />}
          onClick={this.add}
        >
          新增发票信息
        </Button>
      </Form>
    );
  }
}
const BasicFormList = Form.create()(BasicForm);
export default BasicFormList;
